from django import http
from django.http import JsonResponse
from django.shortcuts import render
from utils.response_code import RETCODE

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
import random
from apps.verifications import constants

class SMSCodeView(View):
    # sms_codes/(?P<mobile>1[3-9]\d{9})/
    #1.接收参数
    def get(self,request,mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get("image_code_id")
    #2.检验正则
    #3.对比图像验证码
        #3.1连接redis
        image_client = get_redis_connection("verify_image_code")
        #3.2取出图形验证码
        redis_image_code = image_client.get('img_%s' % uuid)
        #判断服务器返回的验证
        if not redis_image_code:
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})
        #3.3删除图形验证码
        image_client.delete('img_%s' % uuid)
        #3.4判断对比前端的值
        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})
    #4.生成随机 6位
        sms_code = "%06d"%random.randint(0,999999)
    # 5.连接验证码reids数据库
        redis_sms_client = get_redis_connection("sms_code")

        #取出 避免频繁发送短信的标示
        send_flag = redis_sms_client.get("send_flag_%s" % mobile)
        #如果标识存在
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR,'errmsg':"发送短信过于频繁"})

        #创建管道
        p1 = redis_sms_client.pipeline()
    #将redis请求添加到队列里面
        p1.setex('sms_%s' % mobile,300,sms_code)
        #将标识缓存起来
        p1.setex('sms_flag_%s' % mobile,60,1)
    #执行请求
        p1.execute()

    #6.发送短信 --容联云
        from celery_tasks.sms.tasks import send_sms_code_ccp
        # from libs.yuntongxun.sms import CCP
        #                     手机后    6位吗   过期时间   短信模板
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        send_sms_code_ccp.delay(mobile, sms_code)
    #7.返回响应
        print(sms_code)
        return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})


class ImageCodeView(View):
    def get(self,request,uuid):
        """
                :param request: 请求对象
                :param uuid: 唯一标识图形验证码所属于的用户
                :return: image/jpg
                """
        # 生成图片验证码
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        from django_redis import get_redis_connection
        redis_client = get_redis_connection('verify_image_code')
                                            # constants文件里面存在的验证码最大时间 自己写的包
        redis_client.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图片验证码 返回响应对象 图片二进制流
        return http.HttpResponse(image,content_type='image/jpg')